<!-- 这是首页 -->
<template>
  <div>
    <van-nav-bar title="首页" left-text="" right-text="发布" @click-right="goPublic"/>


    <van-empty description="你暂时还没有收藏数据哦~" v-if="list.length==0"/>
    <van-pull-refresh v-model="refreshing" @refresh="onRefresh">
      <van-list :finished="page == total" finished-text="没有更多了" @load="onLoad" style="padding-bottom: 50px">
        <div class="x" style="margin: 25px 15px" v-for="(item, index) in list" :key="index">
          <!--          头像部分-->
          <van-image radius="4" width="50" height="50" :src="item.avtar"/>
          <div class="y flex" style="margin-left: 10px">
            <!--            昵称-->
            <div class="username">{{ item.nickname }}</div>
            <!--            圈子文案内容-->
            <div class="content-text">{{ item.content }}</div>
            <!--            圈子图片内容-->
            <van-grid :column-num="3" style="margin: 8px 0px" v-if="item.images.length > 0" :gutter="1">
              <van-image v-for="(img, index) in item.images" :key="index" style="margin: 1px"
                         @click="ImagePreview(item.images, index)"
                         radius="4" width="100" height="100" :src="img" fit="cover"/>
            </van-grid>
            <div class="x" style="align-items: center">
              <!--              时间-->
              <div class="timestamp flex">{{ parse(item.time) }}</div>
              <!--              点赞的弹窗-->
              <van-popover placement="left" v-model="item.showPopover" theme="dark" trigger="click">
                <template #reference>
                  <van-icon name="ellipsis"/>
                </template>
                <div class="x common">
                  <div class="x" @click="like(item, index)" style="margin-right: 20px; align-items: center">
                    <van-icon name="like-o" size="20" v-if="item.status != 1"/>
                    <van-icon name="like" size="20" v-if="item.status == 1" color="#DF0029"/>
                    <div>{{ item.status == 1 ? "取消" : "点赞" }}</div>
                  </div>
                  <div class="x" style="align-items: center" @click="showComments(item,index)">
                    <van-icon name="comment-o" size="20"/>
                    <div>评论</div>
                  </div>
                </div>
              </van-popover>
            </div>
            <!--            点赞的用户列表-->
            <div class="like-friends" v-if="item.likeUsers.length>0">
              <van-icon name="like-o" size="15" color="#284bad"/>
              <div v-for="(str, i) in item.likeUsers" :key="i">
                {{ str }}<span v-if="i != item.likeUsers.length-1">,</span>
              </div>
            </div>

            <!--           评论的用户列表-->
            <div class="common-root" v-if="item.comments.length>0">
              <div class="common-friends" v-for="(str, i) in item.comments" :key="i" @click="showReplyDialog(index,i)">
                <div>
                  <span class="common-nickname">{{ str.nickname }}<span v-if="str.replyId>0" style="color:#333333;margin: 0 4px">回复</span>{{ str.replyNickname }}:</span>
                  <span class="common-content">
                  {{ str.content }}
                </span>
                </div>
              </div>
            </div>

          </div>

        </div>
      </van-list>
    </van-pull-refresh>

    <!--            底部评论输入框-->
    <van-popup v-model="showComment" position="bottom" :style="{ height: '100px' }">
      <!--      <van-field v-model="comment" placeholder="评论内容"/>-->
      <div style="position: relative">
        <van-field v-model="comment" rows="2" autosize type="textarea" maxlength="250" placeholder="这一刻的想法..."
                   show-word-limit>
        </van-field>
        <van-button @click="Comment" size="mini" style="top: 10px;right: 10px;position: absolute">确认</van-button>
      </div>
    </van-popup>


    <!--            底部评论输入框-->
    <van-popup v-model="showReplyComment" position="bottom" :style="{ height: '100px' }">
      <!--      <van-field v-model="comment" placeholder="评论内容"/>-->
      <div style="position: relative">
        <van-field v-model="comment" rows="2" autosize type="textarea" maxlength="250" :placeholder="'回复  '+tempComment.nickname"
                   show-word-limit>
        </van-field>
        <van-button @click="Comment" size="mini" style="top: 10px;right: 10px;position: absolute">回复</van-button>
      </div>
    </van-popup>
    <!--    点击评论的弹出框-->
    <van-action-sheet v-model="show" cancel-text="取消" :actions="actions" @select="onSelect"/>
  </div>
</template>

<script>
  import axios from '../utils/request'
import {
  weChatTimeFormat
} from "@/utils/time.js";
import {
  Toast
} from "vant";
import Vue from "vue";
import {
  ImagePreview
} from "vant";

export default {
  data() {
    return {
      showComment: false,
      showPopover: false,
      showReplyComment:false,//回复评论时弹出的输入框
      show: false,//控制显示点击评论弹出框
      actions: [{
        name: "回复"
      }, {
        name: "删除",
        color: "#ff5000"
      }],
      list: [], //要显示的圈子数据
      page: 1,
      refreshing: false,
      total: 1, //表示总页码数
      userInfo: {},
      circleId: 0, //用来存储当前操作的圈子ID
      comment: '', //评论的内容
      index: 0, //用来存储当前评论的圈子数组下标
      tempComment:{}//用来存储当前操作的评论实体
    };
  },
  //刷新页面会调用的函数
  mounted() {
    //生命周期函数，刷新页面会调用
    let user = JSON.parse(localStorage.getItem("userInfo"));
    this.userInfo = user;
    this.getList();
  },
  methods: {
    onSelect(obj){
      console.log(obj)
      if(obj.name == "删除"){//调用后台接口进行删除
        axios
            .post("/comment/delete",{id:this.tempComment.id})
            .then((response) => {
              this.show= false//隐藏对话框
                Toast.success(response.data.msg);
                axios
                    .get("/comment/getCommentList?circleId="
                        + this.circleId)
                    .then((obj) => {
                      this.list[this.index].comments = obj.data.data
                    })

            })
      }else {//点击了回复
         this.showReplyComment = true//显示回复评论的对话框
         this.show = false//隐藏当前的对话框
      }
    },
    //显示回复评论的兑话框
    showReplyDialog(index, i) {
      this.circleId = this.list[index].id
      this.index = index
      this.show = true//显示回复对话框
      this.tempComment = this.list[index].comments[i]
      if (this.userInfo.id == this.list[index].comments[i].userId) {//如果两个用户ID不相等，第一个登录用户的ID，第二个是发布这条评论的ID
        this.actions = [{
          name: "回复"
        }, {
          name: "删除",
          color: "#ff5000"
        }]
      } else {
        this.actions = [{
          name: "回复"
        }]
      }
    },
    //评论  回复评论
    Comment() {
      let data = {
        circleId: this.circleId, //当前的评论圈子ID
        content: this.comment,
        replyId:this.tempComment.id?this.tempComment.id:0
      };
      axios
          .post("/comment/add", data, )
          .then((response) => {

              this.comment = ""
              this.showComment = false; //隐藏弹出框
              this.showReplyComment = false; //隐藏弹出框
              Toast.success(response.data.msg);

              axios
                  .get("/comment/getCommentList?circleId=" + this.circleId)
                  .then((obj) => {
                    this.list[this.index].comments = obj.data.data
                  })

          });
    },
    //显示评论对话框
    showComments(item, index) {
      this.showComment = true; //显示对话框
      item.showPopover = false //隐藏
      this.circleId = item.id
      this.index = index
    },
    //点赞或者取消点赞操作
    like(item, index) {
      let data = {
        circleId: item.id,
        status: item.status == 1 ? 0 : 1,
      };
      axios
          .post("/circle/like", data, )
          .then((response) => {

              // if (item.status == 0) {
              //   //点赞添加
              //   item.likeUsers.push(this.userInfo.nickname);
              // } else {
              //   //取消点赞移除 相当于在点赞数组中删除当前用户
              //   item.likeUsers = item.likeUsers.filter((obj) => {
              //     return obj !== this.userInfo.nickname;
              //   });
              // }
              item.showPopover = false; //隐藏弹出框
              item.status = item.status == 1 ? 0 : 1;
              // Vue.set(this.list, index, item)

              axios
                  .get("/circle/getLikeUsers?circleId=" + item.id)
                  .then((obj) => {
                    item.likeUsers = obj.data.data
                  })
              // Toast.success(response.data.msg);

          });
    },
    parse(time) {
      return weChatTimeFormat(time);
    },
    //预览图片 list是要显示的图片列表 index是位置，表示进去后显示的是第几张
    ImagePreview(list, index) {
      ImagePreview({
        images: list,
        startPosition: index,
      });
    },
    goPublic() {
      this.$router.push("/public");
    },
    //下拉刷新触发
    onRefresh() {
      console.log("下拉刷新")
      this.page = 1;
      this.list = [];
      this.getList();
    },
    //滑动到底部触发
    onLoad() {
      console.log("到达底部")
      if (this.page == this.total) {
        return;
      }
      this.page++; //请求下一页的数据
      this.getList();
    },
    getList() {
      axios
          .get("/circle/list?page=" + this.page)
          .then((response) => {
            console.log(response)
            this.refreshing = false;

              for (const item of response.data.data.list) {
                //处理图片数据，因为存入数据库的数据是字符串
                if (!item.images) {
                  item.images = [];
                } else {
                  item.images = JSON.parse(item.images); //字符串转数组对象
                }

                if (!item.likeUsers) {
                  item.likeUsers = [];
                } else {
                  // 8栋码王2,北职吴彦祖,北海
                  item.likeUsers = item.likeUsers.split(",");
                }

              }
              this.list = [...this.list, ...response.data.data.list]; //获取列表 合并两个数组
              this.total = response.data.data.total;
              // Toast.success(response.data.msg);

          });
    },
  },
};
</script>

<style>
.flex {
  flex: 1;
}

.common {
  padding: 12px 24px;
  align-items: center;
  font-size: 14px;
}

.username {
  color: #194e83;
  font-weight: 550;
  font-size: 17px;
}

.content-text {
  color: #000000;
  font-size: 15px;
  margin-top: 5px;
  font-family: "微软雅黑", "宋体";
}

.timestamp {
  color: #999999;
  font-size: 11px;
  margin-bottom: 8px;
}

.y {
  display: flex;
  flex-direction: column;
}

.x {
  display: flex;
  flex-direction: row;
}

.avatar {
  width: 80px;
  height: 80px;
}

.like-friends {
  background: #eee;
  color: #284bad;
  border-radius: 2px;
  padding: 6px 10px;
  display: flex;

  flex-wrap: wrap;
  font-size: 14px;
  font-family: "微软雅黑", "宋体";
  align-items: center;
}

.common-root {
  background: #eee;
  border-radius: 2px;
  padding: 6px 10px;
  display: flex;
  flex-direction: column;
  border-top: 1px solid #ddd;
}

.common-friends {
  display: flex;
  flex-direction: row;
  align-items: start;
}

.common-content {
  color: #333333;
  word-break: break-all;
  font-size: 14px;
}

.common-nickname {
  color: #284bad;
  font-size: 14px;
  font-weight: 700;
  font-family: "微软雅黑", "宋体";
}
</style>
